package com.gitee.qdbp.base.shiro.mgt;

import java.util.Collection;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.session.mgt.DefaultSessionManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.session.mgt.eis.CachingSessionDAO;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;

/**
 * 多Realm统一处理CacheName和CacheKey
 *
 * @author zhaohuihua
 * @version 180830
 */
public class UnifiedWebSecurityManager extends DefaultWebSecurityManager {

    private String activeSessionsCacheName;
    private String authenticationCacheName;
    private String authorizationCacheName;

    protected void afterRealmsSet() {
        super.afterRealmsSet();
        applyCacheNameToRealms();
    }

    protected void applyCacheNameToRealms() {
        SessionManager sessionManager = getSessionManager();
        if (sessionManager instanceof DefaultSessionManager) {
            SessionDAO sessionDao = ((DefaultSessionManager) sessionManager).getSessionDAO();
            if (sessionDao instanceof CachingSessionDAO) {
                ((CachingSessionDAO) sessionDao).setActiveSessionsCacheName(activeSessionsCacheName);
            }
        }
        Collection<Realm> realms = getRealms();
        if (realms != null && !realms.isEmpty()) {
            for (Realm realm : realms) {
                if (realm instanceof AuthenticatingRealm) {
                    AuthenticatingRealm authenticatingRealm = (AuthenticatingRealm) realm;
                    if (authenticationCacheName != null) {
                        authenticatingRealm.setAuthenticationCacheName(authenticationCacheName);
                    }
                }
                if (realm instanceof AuthorizingRealm) {
                    AuthorizingRealm authorizingRealm = (AuthorizingRealm) realm;
                    if (authorizationCacheName != null) {
                        authorizingRealm.setAuthorizationCacheName(authorizationCacheName);
                    }
                }
            }
        }
    }

    public String getActiveSessionsCacheName() {
        return activeSessionsCacheName;
    }

    public void setActiveSessionsCacheName(String activeSessionsCacheName) {
        this.activeSessionsCacheName = activeSessionsCacheName;
    }

    public String getAuthenticationCacheName() {
        return authenticationCacheName;
    }

    public void setAuthenticationCacheName(String authenticationCacheName) {
        this.authenticationCacheName = authenticationCacheName;
    }

    public String getAuthorizationCacheName() {
        return authorizationCacheName;
    }

    public void setAuthorizationCacheName(String authorizationCacheName) {
        this.authorizationCacheName = authorizationCacheName;
    }

}
